package com.hexb.core.config;

import com.hexb.core.jdbc.DynamicRoutingDataSource;
import com.hexb.core.jdbc.MultipleDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.flyway.FlywayDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Package : com.hexb.core.config
 * @Author : hexb
 * @Date : 2018-08-7 14:14
 */
@Configuration
@ConditionalOnProperty(value = "project.multipleDataSource", havingValue = "true")
@Slf4j
public class DynamicDataSourceConfig {

    @Autowired
    private MultipleDataSource multipleDataSource;

    /*
     * 多数据源情况下使用
     * */

    @Bean
    @FlywayDataSource
    public DynamicRoutingDataSource getDynamicRoutingDataSource() {
        DynamicRoutingDataSource dynamicRoutingDataSource = new DynamicRoutingDataSource();
        dynamicRoutingDataSource.setTargetDataSources(multipleDataSource.getDataSources());
        dynamicRoutingDataSource.setDefaultTargetDataSource(multipleDataSource.getDefault());
        dynamicRoutingDataSource.afterPropertiesSet();
        return dynamicRoutingDataSource;
    }
}
